{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from cgi import parse_multipart\n",
    "from multiprocessing.connection import wait\n",
    "import cv2\n",
    "import numpy as np\n",
    "\n",
    "img = cv2.imread(\"picture.jpg\")\n",
    "\n",
    "# 转换为HSV色彩空间以便进行颜色选择\n",
    "imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n",
    "\n",
    "#识别出紫色\n",
    "# 紫色大概为300°，即H在150左右；\n",
    "# 饱和度不能太低，否则就是白色；\n",
    "# 明度不能太低，否则就是黑色\n",
    "lower_purple = np.array([125, 43, 46])\n",
    "upper_purple = np.array([155, 255, 255])\n",
    "mask = cv2.inRange(imgHSV, lowerb=lower_purple, upperb=upper_purple)\n",
    "# 范围选择返回的二值化图像可以作为掩模，按位与提取原图中的紫色部分\n",
    "purple_part = cv2.bitwise_and(img, img, mask=mask)\n",
    "#转化为灰度图\n",
    "gray = cv2.cvtColor(purple_part, cv2.COLOR_BGR2GRAY)\n",
    "# 阈值二值化处理\n",
    "ret, thresh = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY)\n",
    "# 这个函数只支持接收单颜色通道图像，否则报错\n",
    "contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)\n",
    "#寻找轮廓\n",
    "result = cv2.drawContours(purple_part, contours, -1, (0, 0, 255), 2)\n",
    "cnt = contours[0]\n",
    "# 这个函数确定边界的四个点\n",
    "x,y,w,h = cv2.boundingRect(cnt)\n",
    "img = cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)\n",
    "cv2.imshow(\"1\",img)\n",
    "\n",
    "cv2.waitKey(0)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![work][]"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.9.13 ('robomaster')",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.9.13"
  },
  "orig_nbformat": 4,
  "vscode": {
   "interpreter": {
    "hash": "d488e29a69396f7b3bc12ae9eed63c8bfcf92fd19c83d1949b0efc33e68bbd32"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
